package com.strelitzia.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mysql.cj.util.StringUtils;
import com.strelitzia.constant.SessionID;
import com.strelitzia.entity.UserEntity;
import com.strelitzia.exception.StrelitziaException;
import com.strelitzia.filter.CorsFilter;
import com.strelitzia.service.UserService;
import com.strelitzia.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @create 2023/12/14 15:15
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/reg")
    public ResultVo regis(@Valid RegForm regForm, BindingResult result) {
        ResultVo resultVo = new ResultVo();
        if (result.hasErrors()) {
            List<String> message = new ArrayList<>();
            result.getFieldErrors().forEach((item) -> {
                String m = item.getDefaultMessage();
                message.add(m);
            });
            resultVo.setCode(1);
            resultVo.setMsg("提交的数据不合法");
            resultVo.setData(message);
        } else {
            String message = userService.regis(regForm);
            if ("".equals(message)) {
                resultVo.setMsg("注册成功");
            } else {
                resultVo.setCode(1);
                resultVo.setMsg(message);
            }
        }
        return resultVo;
    }

    @PostMapping("/log")
    public ResultVo login(@Valid LoginForm loginForm, BindingResult result, HttpServletResponse response, HttpSession session) {
        ResultVo resultVo = new ResultVo();
        if (result.hasErrors()) {
            List<String> message = new ArrayList<>();
            result.getFieldErrors().forEach((item) -> {
                String m = item.getDefaultMessage();
                message.add(m);
            });
            resultVo.setCode(1);
            resultVo.setMsg("提交的数据不合法");
            resultVo.setData(message);
        } else {
            String verifyCode = (String) session.getAttribute(SessionID.VALIDATE_CODE);
            if (StringUtils.isNullOrEmpty(verifyCode) || !verifyCode.equalsIgnoreCase(loginForm.getCode())) {
                resultVo.setCode(1);
                resultVo.setMsg("验证码错误");
            } else {
                UserEntity userEntity = userService.login(loginForm);
                if (userEntity != null) {
                    resultVo.setMsg("登录成功");
                    resultVo.setData(userEntity);
                    if (loginForm.getAuto()) {
                        Cookie cookie = new Cookie(SessionID.LOGIN_USER, userEntity.getId().toString());
                        cookie.setPath("/");
                        cookie.setMaxAge(30 * 24 * 60 * 60);
                        response.addCookie(cookie);
                    } else {
                        session.setAttribute(SessionID.LOGIN_USER, userEntity.getId());
                    }
                } else {
                    resultVo.setCode(1);
                    resultVo.setMsg("用户名或密码错误");
                }
            }
        }
        return resultVo;
    }

    @PostMapping("/update")
    public ResultVo update(UpdateUserForm form) {
        ResultVo resultVo = new ResultVo();
        try {
            UserEntity userEntity = userService.updateUser(form);
            if (userEntity != null) {
                resultVo.setData(userEntity);
                resultVo.setMsg("保存成功");
            } else {
                resultVo.setCode(1);
                resultVo.setMsg("修改失败");
            }
        } catch (StrelitziaException e) {
            resultVo.setCode(1);
            resultVo.setMsg(e.getMessage());
        }
        return resultVo;
    }

    @GetMapping("/update/{email}")
    public ResultVo updateEmail(@PathVariable String email) {
        ResultVo resultVo = new ResultVo();
        UserEntity userEntity = new UserEntity();
        userEntity.setId(CorsFilter.loginUserId.get());
        userEntity.setEmail(email);
        int count = userService.count(new QueryWrapper<UserEntity>().eq("email", email));
        if (count == 0) {
            try {
                userService.updateById(userEntity);
                resultVo.setMsg("修改成功");
            } catch (Exception e) {
                resultVo.setCode(1);
                resultVo.setMsg("保存失败，服务器错误");
            }
        } else {
            resultVo.setCode(1);
            resultVo.setMsg("该邮箱以注册，请尝试更换邮箱");
        }

        return resultVo;
    }

    @GetMapping("/status/{status}")
    public ResultVo status(@PathVariable Integer status) {
        ResultVo resultVo = new ResultVo();
        try {
            resultVo.setData(userService.setStatus(status));
            ;
        } catch (Exception e) {
            resultVo.setCode(1);
            resultVo.setMsg("修改状态失败");
        }
        return resultVo;
    }

    @GetMapping()
    public ResultVo getUser() {
        ResultVo resultVo = new ResultVo();
        Integer useId = CorsFilter.loginUserId.get();
        if (useId != null) {
            userService.setStatus(1);
            resultVo.setData(userService.getById(useId));
        } else {
            resultVo.setCode(1);
        }
        return resultVo;
    }

    @GetMapping("/logout")
    public void logout(HttpServletResponse response, HttpSession session) {
        userService.setStatus(2);
        session.removeAttribute(SessionID.LOGIN_USER);
        Cookie cookie = new Cookie(SessionID.LOGIN_USER, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    @GetMapping("/setPassword/{password}")
    public ResultVo setPassword(@PathVariable String password) {
        ResultVo resultVo = new ResultVo();
        UserEntity userEntity = new UserEntity();
        userEntity.setId(CorsFilter.loginUserId.get());
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String pwd = passwordEncoder.encode(password);
        userEntity.setPassword(pwd);

        try {
            userService.updateById(userEntity);
        } catch (Exception e) {
            resultVo.setCode(1);
            resultVo.setMsg("服务器错误");
        }
        return resultVo;
    }


    @GetMapping("/{id}")
    public ResultVo getUser(@PathVariable("id") Integer id) {
        ResultVo resultVo = new ResultVo();
        try {
            resultVo.setData(userService.get(id));
        } catch (Exception e) {
            resultVo.setCode(1);
            resultVo.setMsg("服务器错误");
        }

        return resultVo;
    }

    @GetMapping("/search/{keyword}")
    public ResultVo searchUser(@PathVariable("keyword") String keyword) {
        ResultVo resultVo = new ResultVo();
        try {
            Integer id = userService.getKeyword(keyword);
            if (id == 0) {
                resultVo.setMsg("未找到该用户信息");
            }
            resultVo.setData(id);
        } catch (Exception e) {
            resultVo.setCode(1);
            resultVo.setMsg("服务器错误");
        }

        return resultVo;
    }
}
